<?php
/**
 * 开始工单
 * User: Administrator
 * Date: 2018/8/6/006
 * Time: 21:05
 */

namespace app\lib\Order\OrderOption;


use app\lib\Order\IsOrder\IsOrder;
use app\lib\Order\OrderExtensionConfig\OrderBindingExtension;
use app\lib\Order\OrderInfo\GetOrderMoney;
use app\lib\Order\OrderInfo\UpdateOrderStatus;
use app\lib\Order\OrderMoney\AddOrderMoneyRecord;
use app\lib\Order\OrderNotice\OrderNotice;
use app\lib\Order\OrderPaymentNotice\AddOrderNotice;

class OrderStartOption
{
    protected $orderId;
    protected $opUid;
    public function __construct($orderId,$opUid)
    {
        $this->opUid   = $opUid;
        $this->orderId = $orderId;
    }

    /**
     * 验证
     * @throws \Exception
     */
    protected function check(){
        $isOrder =  (new IsOrder($this->orderId));
        if(!$isOrder->isNoStartOrder()){
            exception('工单状态异常');
        }
    }

    /**
     * 工地开始任务
     * @return bool
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function save(){
        /*修改工单状态*/
        (new UpdateOrderStatus($this->orderId,$this->opUid))->getCarryOrderStatus()->save();
        /*交款信息实例化*/
        $orderMoneyModel =  (new GetOrderMoney($this->orderId,false));
        /*第一期未交款*/
        if(!($orderMoneyModel->isFirstMoney())){
            $model = new AddOrderNotice();
            /*获取未交款id*/
            $info =  $orderMoneyModel->getNoPayRecord();
            /*生成交款通知记录*/
            $model->setOpUid($this->opUid)->setOrderId($this->orderId)->setMoneyId($info['id'])
                ->setContent('发布工单催款，工单['.$info['name'].']')->AddOrderNoPayNotice();
            /*生成待交款信息*/
            (new AddOrderMoneyRecord())->setOrderMoneyId($info['id'])->noPay();
            /*挂上未交款标签*/
            (new OrderBindingExtension($this->orderId,$this->opUid,2))->save();
        }
        /*通知*/
        (new OrderNotice($this->orderId,$this->opUid))->releaseTask();
        /*记入工单日志*/
        $log =  new OrderOptionLog($this->orderId);
        $log->setOptionType('STARTTACK');
        $log->setOptionUserId($this->opUid);
        $log->setSubmitParameter('');
        $log->setOptionContent('工单id为'.$this->orderId.'工单开始');
        $log->save();
        return true;
    }
}